package com.auto.learning.activity;

import java.util.ArrayList;

import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.media.MediaPlayer.OnErrorListener;
import android.media.MediaPlayer.OnPreparedListener;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Html;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewTreeObserver;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.RelativeLayout.LayoutParams;
import android.widget.ScrollView;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.TextView;
import android.widget.VideoView;

import com.auto.learning.R;
import com.auto.learning.bean.BookBean;
import com.auto.learning.bean.VideoBean;
import com.auto.learning.event.EventBus;
import com.auto.learning.event.listener.DialogListener;
import com.auto.learning.net.Cache;
import com.auto.learning.net.HttpRequestHelper;
import com.auto.learning.service.MusicPlayManager;
import com.auto.learning.tools.CommonMethod;
import com.auto.learning.tools.FastBlur;
import com.auto.learning.tools.TemporaryVariable;
import com.auto.learning.view.CommonAlertDialog;
import com.auto.learning.view.SharedPreferencesUtils;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.squareup.otto.Subscribe;
import com.squareup.otto.ThreadEnforcer;

public class VideoPlayActivity extends Activity implements OnPreparedListener,OnCompletionListener,
		OnErrorListener,OnClickListener,OnSeekBarChangeListener{
	
	private VideoBean videoBean;
	private TextView tv_titlename,tv_time,tv_abous,tv_to_read,tv_titlename_2,tv_tro_slog;
	private VideoView videoview;
	private ImageView image_render,image_operator,image_fullscreen;
	private View view;
	private RelativeLayout rel_operator,rel_intro,rel_video,rel_bottom;
	private ScrollView scroll_intro;
	private SeekBar my_seekbar;
	private int max = 0;
	private final static int DEFAULT_OPERATOR = 5;  //默认显示时间
	private int i = DEFAULT_OPERATOR;
	private LinearLayout activity_base_back,activity_base_title,activity_base_title_2,activity_base_back_2;
	private int time = HttpRequestHelper.BLUR_DEFAULT_TIMES;
	//判断是否播放	0代表未播放 ，1代表在播放
	private int isplay=0;
	private int currentPosition = 0;
	
	private int x = 0;
	
	private boolean hasPlay = false;
	
	private Handler handler = new Handler(){
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case HttpRequestHelper.GET_LOCAL_BOOKBEAN_SUCCESS:
				final BookBean bean = (BookBean) msg.obj;
				if (bean != null) {
					if (videoview != null && videoview.isPlaying()) {
						x = 1;
						image_operator.performClick();
						isplay = 1;
					}else {
						x = 2;
					}
					switch (CommonMethod.getNetworkState(VideoPlayActivity.this)) {
					case 0:
						CommonMethod.makeNotice(VideoPlayActivity.this, getResources().getString(R.string.connect_err_io));
						break;
					case 1:
						TemporaryVariable.read_list.clear();
						TemporaryVariable.read_list.add(bean.getBookId());
						handler.postDelayed(new Runnable() {
							public void run() {
								ArrayList<BookBean> m_list = new ArrayList<BookBean>();
								m_list.add(bean);
								MusicPlayManager.getInstance(VideoPlayActivity.this).setPlayList(m_list).setBookId(bean.getBookId()).play();
							}
						}, 1500);
						Intent intent = new Intent(VideoPlayActivity.this, PlayActivity.class);
						intent.putExtra("bookId", bean.getBookId());
						intent.putExtra("faceImg", TextUtils.isEmpty(bean.getFaceImg()) ? "" : bean.getFaceImg());
						intent.putExtra("canRead",bean.getCanRead());
						intent.putExtra("needBuy",bean.getNeedBuy());
						startActivity(intent);
						break;
					case 2:
						CommonAlertDialog ad = new CommonAlertDialog(VideoPlayActivity.this);
						ad.setTextMessage("当前为移动网络，是否继续播放？");
						ad.setShowTitle(true);
						String[] aa = {"继续","取消"};
						ad.setBtns(new DialogListener() {

							@Override
							public void okButtonClick(Dialog dialog) {
								dialog.dismiss();
								TemporaryVariable.read_list.clear();
								TemporaryVariable.read_list.add(bean.getBookId());
								handler.postDelayed(new Runnable() {
									public void run() {
										ArrayList<BookBean> m_list = new ArrayList<BookBean>();
										m_list.add(bean);
										MusicPlayManager.getInstance(VideoPlayActivity.this).setPlayList(m_list).setBookId(bean.getBookId()).play();
									}
								}, 1500);
								Intent intent = new Intent(VideoPlayActivity.this, PlayActivity.class);
								intent.putExtra("bookId", bean.getBookId());
								intent.putExtra("faceImg", TextUtils.isEmpty(bean.getFaceImg()) ? "" : bean.getFaceImg());
								intent.putExtra("canRead",bean.getCanRead());
								intent.putExtra("needBuy",bean.getNeedBuy());
								startActivity(intent);
							}

							@Override
							public void cancelButtonClick(Dialog dialog) {
								dialog.dismiss();
							}

							@Override
							public void otherButtonClick(Dialog dialog) {
								dialog.dismiss();
							}}, aa);
						ad.show();
						break;
					}
				}
				break;
			}
		};
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
		super.onCreate(savedInstanceState);
		setContentView(R.layout.videoplay_activity);
		initView();
		regeditEvent();
	}
	
	@Subscribe
	public void onScreenOffEvent(Integer m){
		if (videoview != null && videoview.isPlaying()) {
			videoview.pause();
			image_operator.setImageResource(R.drawable.play_small);
		}
	}
	
	private void regeditEvent(){
		EventBus.getEventBus("m_video_play_status", ThreadEnforcer.MAIN).register(this);
	}
	
	private void unregeditEvent(){
		EventBus.getEventBus("m_video_play_status", ThreadEnforcer.MAIN).unregister(this);
	}
	
	@Override
	protected void onResume() {
//		videoview.resume();
		if (currentPosition > 0) {
			i = DEFAULT_OPERATOR;
			if (videoview != null) {
				if(isplay==1){
					videoview.start();
					videoview.seekTo(currentPosition);
					image_operator.setImageResource(R.drawable.pause_small);
				}
//				videoview.start();
//				videoview.seekTo(currentPosition);
//				image_operator.setImageResource(R.drawable.pause_small);
//				videoview.pause();
			}
		}
		super.onResume();
	}
	
	@Override
	protected void onDestroy() {
		unregeditEvent();
		super.onDestroy();
	}
	
	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
		
		image_operator.setImageResource(R.drawable.play_small);
		videoview.pause();
	}
	private void initView(){
		full(false);
		Intent intent = getIntent();
		videoBean = (VideoBean) intent.getSerializableExtra("m_bean");
		tv_tro_slog = (TextView) findViewById(R.id.tv_tro_slog);
		tv_to_read = (TextView) findViewById(R.id.tv_to_read);
		tv_to_read.setOnClickListener(this);
		scroll_intro = (ScrollView) findViewById(R.id.scroll_intro);
		rel_operator = (RelativeLayout) findViewById(R.id.rel_operator);
		rel_intro = (RelativeLayout) findViewById(R.id.rel_intro);
		rel_bottom = (RelativeLayout) findViewById(R.id.rel_bottom);
		image_operator = (ImageView) findViewById(R.id.image_operator);
		my_seekbar = (SeekBar) findViewById(R.id.my_seekbar);
		tv_time = (TextView) findViewById(R.id.tv_time);
		image_fullscreen = (ImageView) findViewById(R.id.image_fullscreen);
		rel_video = (RelativeLayout) findViewById(R.id.rel_video);
		tv_abous = (TextView) findViewById(R.id.tv_abous);
		rel_video.setOnClickListener(this);
		rel_operator.getBackground().setAlpha(100);
		rel_bottom.getBackground().setAlpha(127);
		scroll_intro.getBackground().setAlpha(127);
		activity_base_title = (LinearLayout) findViewById(R.id.activity_base_title);
		activity_base_back = (LinearLayout) findViewById(R.id.activity_base_back);
		tv_titlename = (TextView) findViewById(R.id.tv_titlename);
		activity_base_title_2 = (LinearLayout) findViewById(R.id.activity_base_title_2);
		activity_base_back_2 = (LinearLayout) findViewById(R.id.activity_base_back_2);
		tv_titlename_2 = (TextView) findViewById(R.id.tv_titlename_2);
		videoview = (VideoView) findViewById(R.id.videoview);
		videoview.setOnClickListener(this);
		image_render = (ImageView) findViewById(R.id.image_render);
		view = findViewById(R.id.text);
		applyBlur();
		ImageLoader.getInstance().displayImage(videoBean.getVideoImg(), image_render);
		tv_tro_slog.setText(videoBean.getSlogan()+"");
		if (!TextUtils.isEmpty(videoBean.getIntroduce())) {
			tv_abous.setText(Html.fromHtml(videoBean.getIntroduce()));
		}
		activity_base_title.getBackground().setAlpha(127);
		activity_base_back.setTag("0");
		activity_base_back.setOnClickListener(this);
		activity_base_back_2.setOnClickListener(this);
		my_seekbar.setOnSeekBarChangeListener(this);
		image_operator.setOnClickListener(this);
		image_fullscreen.setOnClickListener(this);
		activity_base_title.setVisibility(View.GONE);
		if (videoBean != null) {
			tv_titlename.setText(videoBean.getTitle());
			tv_titlename_2.setText(videoBean.getTitle());
			checkNet();
		}
		if (videoBean.getBookId() == 0) {
			tv_to_read.setVisibility(View.GONE);
		}
	}
	
	private void play(){
		isplay=1;
		hasPlay = true;
		videoview.setVideoURI(Uri.parse(videoBean.getVideoUrl()));
		videoview.setOnPreparedListener(this);
		videoview.setOnCompletionListener(this);
		videoview.setOnErrorListener(this);
		videoview.start();
		handler.removeCallbacks(runnable);
		handler.postDelayed(runnable, 1000);
	}
	
	private void checkNet(){
		if ((boolean) SharedPreferencesUtils.getParam(this, HttpRequestHelper.DWONLOAD_PLAY_CONTINUE, false)) {
			play();
		}else {
			switch (CommonMethod.getNetworkState(VideoPlayActivity.this)) {
			case 0:
				CommonMethod.makeNotice(VideoPlayActivity.this, getResources().getString(R.string.connect_err_io));
				finish();
				break;
			case 1:
				play();
				break;
			case 2:
				CommonAlertDialog alertDialog = new CommonAlertDialog(this);
				alertDialog.setTextMessage(getResources().getString(R.string.net_ismobile_connect));
				alertDialog.setShowTitle(true);
				String[] a = {getResources().getString(R.string.app_continue),getResources().getString(R.string.app_cancel)};
				alertDialog.setBtns(new DialogListener() {
					@Override
					public void okButtonClick(Dialog dialog) {
						play();
						dialog.dismiss();
					}
	
					@Override
					public void cancelButtonClick(Dialog dialog) {
						image_operator.setImageResource(R.drawable.play_small);
						dialog.dismiss();
					}
	
					@Override
					public void otherButtonClick(Dialog dialog) {
						dialog.dismiss();
					}}, a);
				alertDialog.show();
				break;
			}
		}
	}
	
	@Override
	public void onPrepared(MediaPlayer mp) {
		EventBus.getEventBus("m_pause_only").post("");
		image_operator.setImageResource(R.drawable.pause_small);
		max = mp.getDuration();
		my_seekbar.setMax(max);
		handler.postDelayed(runnable, 1000);
		handler.postDelayed(controll, 1000);
		if (x == 2) {
			videoview.pause();
			image_operator.setImageResource(R.drawable.play_small);
			x = 0;
		}
		if (videoBean != null && videoBean.getId() > 0) {
			HttpRequestHelper.addVideoPlayNum(this, videoBean.getId());
		}
	}
	
	@Override
	public void onCompletion(MediaPlayer mp) {
		handler.removeCallbacks(runnable);
	}
	
	@Override
	public boolean onError(MediaPlayer mp, int what, int extra) {
		return false;
	}
	
	
	Runnable runnable =new Runnable() {
		
		@Override
		public void run() {
			if (videoview != null && videoview.isPlaying()) {
				int current = videoview.getCurrentPosition();
				currentPosition = current;
				my_seekbar.setProgress(current);
				tv_time.setText(getNowTime(current)+"/"+getNowTime(max));
			}
			handler.postDelayed(runnable, 1000);
		}
	};
	
	Runnable controll = new Runnable() {
		
		@Override
		public void run() {
			String tag = activity_base_back.getTag().toString();
			if (i > 0) {
				i --;
				rel_operator.setVisibility(View.VISIBLE);
				if (tag.equals("0")) {
					activity_base_title.setVisibility(View.GONE);
				}else {
					activity_base_title.setVisibility(View.VISIBLE);
				}
			} else {
				rel_operator.setVisibility(View.GONE);
				activity_base_title.setVisibility(View.GONE);
			}
			
			handler.postDelayed(controll, 1000);
		}
	};
	
	
	/**
	 * 时间转换
	 * @param nowDuration
	 * @return
	 */
	private String getNowTime(int nowDuration) {
		String sendmin = null;
		int nowTime = nowDuration / 1000;
		int min = nowTime / 60;
		int sec = nowTime % 60;
		if (min < 10) {
			sendmin = "0" + min;
		} else {
			sendmin = min + "";
		}
		if (sec < 10) {
			return sendmin + ":0" + sec;
		} else {
			return sendmin + ":" + sec;
		}
	}
	
	
	/***
	 * 处理高斯模糊
	 */
	public void applyBlur() {
		image_render.getViewTreeObserver().addOnPreDrawListener(
				new ViewTreeObserver.OnPreDrawListener() {
					@Override
					public boolean onPreDraw() {
						if (time > 0) {
							time --;
						}else {
							image_render.getViewTreeObserver().removeOnPreDrawListener(this);
						}
						image_render.buildDrawingCache();
						Bitmap bmp = image_render.getDrawingCache();
						FastBlur.blur(bmp, view, VideoPlayActivity.this);
						return true;
					}
				});
	}
	


	
	@Override
	public void onConfigurationChanged(Configuration newConfig) {
		super.onConfigurationChanged(newConfig);
		LayoutParams params = (LayoutParams) rel_video.getLayoutParams();
		if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) { //小屏幕
			rel_intro.setVisibility(View.VISIBLE);
			rel_bottom.setVisibility(View.VISIBLE);
			params.height = CommonMethod.dip2px(VideoPlayActivity.this, 200);
			params.width = LayoutParams.MATCH_PARENT;
			rel_video.setLayoutParams(params);
			activity_base_back.setTag("0");
			activity_base_title_2.setVisibility(View.VISIBLE);
			activity_base_title.setVisibility(View.GONE);
			image_fullscreen.setImageResource(R.drawable.v_fullscreen);
			full(false);
		} else if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) { //大屏幕
			rel_intro.setVisibility(View.GONE);
			rel_bottom.setVisibility(View.GONE);
			params.height = LayoutParams.MATCH_PARENT;
			params.width = LayoutParams.MATCH_PARENT;
			rel_video.setLayoutParams(params);
			activity_base_back.setTag("1");
			activity_base_title_2.setVisibility(View.GONE);
			activity_base_title.setVisibility(View.VISIBLE);
			image_fullscreen.setImageResource(R.drawable.v_windowscreen);
			full(true);
		}
		
		LayoutParams v_params = (LayoutParams) videoview.getLayoutParams();
		v_params.width = LayoutParams.MATCH_PARENT;
		v_params.height = LayoutParams.MATCH_PARENT;
		videoview.setLayoutParams(v_params);
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.activity_base_back:
			if (v.getTag().toString().equals("0")) {
				finish();
			}else if (v.getTag().toString().equals("1")){
				setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
			}
			break;
		case R.id.rel_video:
			i = DEFAULT_OPERATOR;
			rel_operator.setVisibility(View.VISIBLE);
			if (activity_base_back.getTag().toString().equals("0")) {
				activity_base_title.setVisibility(View.GONE);
			}else {
				activity_base_title.setVisibility(View.VISIBLE);
			}
			break;
		case R.id.image_operator:
			if (videoview.isPlaying()) {
				isplay=0;
				image_operator.setImageResource(R.drawable.play_small);
				videoview.pause();
			}else {
				isplay=1;
				image_operator.setImageResource(R.drawable.pause_small);
				if (hasPlay) {
					handler.removeCallbacks(runnable);
					handler.postDelayed(runnable, 1000);
					videoview.start();
				}else {
					play();
				}
			}
			break;
		case R.id.image_fullscreen:
			if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
				setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);// 横屏
			} else if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) {
				setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);// 竖屏
			}
			break;
		case R.id.tv_to_read:
			if (videoBean != null && videoBean.getBookId() != 0) {
				Cache.getBookBeanById(VideoPlayActivity.this,videoBean.getBookId(),handler);
			}
			break;
		case R.id.activity_base_back_2:
			finish();
			break;
		}
		
	}

	@Override
	public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
		if (fromUser) {
			videoview.seekTo(progress);
		}
	}

	@Override
	public void onStartTrackingTouch(SeekBar seekBar) {
		
	}

	@Override
	public void onStopTrackingTouch(SeekBar seekBar) {
		
	}
	
	private void full(boolean enable) {
        if (enable) {
            WindowManager.LayoutParams lp = getWindow().getAttributes();
            lp.flags |= WindowManager.LayoutParams.FLAG_FULLSCREEN;
            getWindow().setAttributes(lp);
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);
        } else {
            WindowManager.LayoutParams attr = getWindow().getAttributes();
            attr.flags &= (~WindowManager.LayoutParams.FLAG_FULLSCREEN);
            getWindow().setAttributes(attr);
            getWindow().clearFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);
        }
    }
	
}
